package com.acmen.easyapi.util;

import com.acmen.easyapi.annotation.EnumDesc;
import com.acmen.easyapi.annotation.EnumValue;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @author acmen
 * 获取枚举值
 */
public class EnumUtil {
    private final static List<String> codeFieldNames = Arrays.asList("code","value");
    private final static List<String> descFieldNames = Arrays.asList("desc","name");

    public static Object getEnumValue(Object enumObj){
        Field[] fields = enumObj.getClass().getDeclaredFields();
        return getEnumValue(enumObj,fields);
    }
    public static Object getEnumValue(Object enumObj,Field[] fields) {
        for (Field field : fields) {
            EnumValue enumValue = ClassUtil.getAnnotation(field, EnumValue.class);
            if (enumValue!=null) {
                return ClassUtil.getFieldValue(enumObj,field);
            }
        }
        for (Field field : fields) {
            if(codeFieldNames.contains(field.getName())){
                return ClassUtil.getFieldValue(enumObj,field);
            }
        }
        return enumObj.toString();
    }

    public static Object getEnumDesc(Object enumObj){
        Field[] fields = enumObj.getClass().getDeclaredFields();
        return getEnumDesc(enumObj,fields);
    }

    public static Object getEnumDesc(Object enumObj,Field[] fields) {
        for (Field field : fields) {
            EnumDesc enumDesc = ClassUtil.getAnnotation(field, EnumDesc.class);
            if (enumDesc!=null) {
                return ClassUtil.getFieldValue(enumObj,field);
            }
        }
        for (Field field : fields) {
            if(descFieldNames.contains(field.getName())){
                return ClassUtil.getFieldValue(enumObj,field);
            }
        }
        return null;
    }
}
